package com.module.app.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.module.frame.converter.MyTypeAdapterFactory;
import com.module.third.ThirdUtil;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * @author bsnl_yanxuwen
 * @date 2020/9/24 14:48
 * Description :
 * Gson 处理
 */
public class GsonUtils {

    public static Gson getGson() {
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new MyTypeAdapterFactory<>()).create();
        return gson;
    }

    /**
     * Gosn解析，会自动处理数据类型不一样等问题
     */
    public static <T> T fromJson(String json, Type type) {
        return getGson().fromJson(json, type);
    }

    public static String toJson(Object o) {
        return getGson().toJson(o);
    }

    /**
     * 根据json字符串返回Map对象
     *
     * @param json
     * @return
     */
    public static Map<String, Object> toMap(String json) {
        return ThirdUtil.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
    }
}
